﻿Public Class CreateTrigger
    Implements ITrigger

    Public Event CreateTableTrigger(ByVal table As String) Implements IListenDb.ITrigger.CreateTableTrigger
    Public Event DeleteTableTrigger(ByVal table As String) Implements IListenDb.ITrigger.DeleteTableTrigger
    Public Event UpdateTableTrigger(ByVal table As String) Implements IListenDb.ITrigger.UpdateTableTrigger

    Public Function CreateTrigger(ByVal dbConnection As System.Data.Common.DbConnection, ByVal 前缀 As String) As Boolean Implements IListenDb.ITrigger.CreateTrigger

        '删除标准创建的触发器
        CommonConUtil.ExecuteSql(" drop trigger " & 前缀 & "_I_HAN07X002JIKKOU")
        RaiseEvent CreateTableTrigger("删除触发器 " & 前缀 & "_I_HAN07X002JIKKOU")

        Dim sqlCreate As String = ""
        Dim sql As String = ""

        Dim dt表 As New DataTable
        Dim dt列 As New DataTable
        Dim dt表列 As New DataTable

        '创建
        sqlCreate = CommonTableToTrigger.ConvertToInsertTriggerHAN07X002JIKKOU(前缀)
        CommonConUtil.ExecuteSql(sqlCreate)
        RaiseEvent CreateTableTrigger("创建特殊插入触发器 " & 前缀 & "_I_A_HAN07X002JIKKOU")

    End Function

    Public Function DeleteTrigger(ByVal dbConnection As System.Data.Common.DbConnection, ByVal 前缀 As String) As Boolean Implements IListenDb.ITrigger.DeleteTrigger

        Dim sqlCreate As String = ""

        '创建
        CommonConUtil.ExecuteSql(" drop trigger " & 前缀 & "_I_A_HAN07X002JIKKOU")
        RaiseEvent CreateTableTrigger("删除特殊插入触发器 " & 前缀 & "_I_A_HAN07X002JIKKOU")

    End Function

    Public Function UpdateTrigger(ByVal dbConnection As System.Data.Common.DbConnection, ByVal 前缀 As String) As Boolean Implements IListenDb.ITrigger.UpdateTrigger

        Dim sqlCreate As String = ""
        Dim sql As String = ""

        Dim dt表 As New DataTable
        Dim dt列 As New DataTable
        Dim dt表列 As New DataTable

        '获取所有表
        sql = "select name,object_id from sys.tables"
        dt表 = CommonConUtil.GetTable(sql)

        '获取所有列
        sql = " select c.object_id,c.name columnname,c.max_length,c.precision,c.scale,t.name typename from sys.columns c "
        sql += " LEFT JOIN sys.types t"
        sql += " on c.system_type_id=t.system_type_id"
        sql += " where t.name<>'sysname'"
        dt列 = CommonConUtil.GetTable(sql)

        Dim dv As DataView = dt列.DefaultView

        For rowTable As Integer = 0 To dt表.Rows.Count - 1

            dv.RowFilter = "object_id=" & CStr(dt表.Rows(rowTable)("object_id"))
            dt表列 = dv.ToTable

            If Not dt表.Rows(rowTable)("name").ToString.StartsWith(前缀) Then

                sqlCreate = CommonTableToTrigger.ConvertToUpdateTrigger(dt表列, CStr(dt表.Rows(rowTable)("name")), 前缀)
                CommonConUtil.ExecuteSql(sqlCreate)
                RaiseEvent CreateTableTrigger("修改更新触发器 " & 前缀 & "_U_" & CStr(dt表.Rows(rowTable)("name")))

            End If
        Next

    End Function

End Class

